import requests
import base64
import json

# 定义容器的URL地址和端口
url = "http://localhost:8091"  # 根据Docker映射的端口信息

import yaml

# 读取 YAML 文件
with open('class.yaml', 'r') as file:
    try:
        class_date = yaml.safe_load(file)

    except yaml.YAMLError as exc:
        print(f"Error reading YAML file: {exc}")

# 读取图片并进行base64编码
def encode_image(image_path):
    with open(image_path, "rb") as image_file:
        encoded_image = base64.b64encode(image_file.read()).decode('utf-8')
    return encoded_image


# 创建测试请求
def test_yolov8(image_path, threshold=0.5):
    encoded_image = encode_image(image_path)

    # 构造请求数据
    data = {
        "image": encoded_image,
        "task": "6"
    }

    # 发送POST请求到容器
    response = requests.post(f"{url}/", data=json.dumps(data), headers={"Content-Type": "application/json"})

    # 处理响应
    if response.status_code == 200:
        print("Detection Results:", response.json())
        result = response.json()
        conference = result['logits']
        label = result['phrases']

        print(conference)


        print(label)
        print(result['boxes'])
    else:
        print("Failed to get response. Status code:", response.status_code)


# 调用测试
if __name__ == "__main__":
    # 输入图片路径进行测试
    image_path = "cat.jpg"  # 替换为你要测试的图片路径
    test_yolov8(image_path)